package com.ioftv.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.ioftv.dto.LabelerTaskPackageExcelDTO;
import com.ioftv.entity.LabelerTaskPackage;
import com.ioftv.service.LabelerTaskPackageService;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;

/**
 * 标注员任务包Excel导入监听器
 */
@Slf4j
public class LabelerTaskPackageImportListener implements ReadListener<LabelerTaskPackageExcelDTO> {

    private LabelerTaskPackageService labelerTaskPackageService;
    private List<LabelerTaskPackageExcelDTO> cachedDataList = new ArrayList<>();
    private static final int BATCH_COUNT = 100;
    
    // 用于返回导入结果
    private int totalRows = 0;
    private int successRows = 0;
    private int failRows = 0;
    private List<String> errorMessages = new ArrayList<>();

    public LabelerTaskPackageImportListener(LabelerTaskPackageService labelerTaskPackageService) {
        this.labelerTaskPackageService = labelerTaskPackageService;
    }

    @Override
    public void invoke(LabelerTaskPackageExcelDTO data, AnalysisContext context) {
        log.debug("解析到一条数据: {}", data);
        totalRows++;
        int rowNumber = context.readRowHolder().getRowIndex() + 1;
        
        // 数据校验
        if (data.getLabelerName() == null || data.getLabelerName().trim().isEmpty()) {
            errorMessages.add("第" + rowNumber + "行: 标注员姓名不能为空");
            failRows++;
            return;
        }
        
        if (data.getReceiveTime() == null) {
            errorMessages.add("第" + rowNumber + "行: 领取时间不能为空");
            failRows++;
            return;
        }
        
        if (data.getAccount() == null || data.getAccount().trim().isEmpty()) {
            errorMessages.add("第" + rowNumber + "行: 账号不能为空");
            failRows++;
            return;
        }
        
        if (data.getTaskBatch() == null || data.getTaskBatch().trim().isEmpty()) {
            errorMessages.add("第" + rowNumber + "行: 任务批次不能为空");
            failRows++;
            return;
        }
        
        if (data.getPackageId() == null || data.getPackageId().trim().isEmpty()) {
            errorMessages.add("第" + rowNumber + "行: 提包Id不能为空");
            failRows++;
            return;
        }
        
        cachedDataList.add(data);
        successRows++;
        
        // 达到BATCH_COUNT了，需要去存储一次数据库，防止数据几万条数据在内存，容易OOM
        if (cachedDataList.size() >= BATCH_COUNT) {
            saveData();
            // 存储完成清理 list
            cachedDataList.clear();
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        // 这里也要保存数据，确保最后遗留的数据也存储到数据库
        saveData();
        log.info("所有数据解析完成！");
    }

    /**
     * 加上存储数据库
     */
    private void saveData() {
        log.info("{}条数据，开始存储数据库！", cachedDataList.size());
        for (LabelerTaskPackageExcelDTO excelDTO : cachedDataList) {
            LabelerTaskPackage taskPackage = new LabelerTaskPackage();
            taskPackage.setLabelerName(excelDTO.getLabelerName());
            taskPackage.setReceiveTime(excelDTO.getReceiveTime());
            taskPackage.setAccount(excelDTO.getAccount());
            taskPackage.setTaskBatch(excelDTO.getTaskBatch());
            taskPackage.setPackageId(excelDTO.getPackageId());
            taskPackage.setDeliveryTime(excelDTO.getDeliveryTime());
            taskPackage.setDeliveryBoxCount(excelDTO.getDeliveryBoxCount());
            taskPackage.setRepairCount(excelDTO.getRepairCount());
            taskPackage.setFinalBoxCount(excelDTO.getFinalBoxCount());
            taskPackage.setStatus(excelDTO.getStatus() != null ? excelDTO.getStatus() : "进行中");
            
            labelerTaskPackageService.save(taskPackage);
        }
        log.info("存储数据库成功！");
    }
    
    // Getters for import result
    public int getTotalRows() {
        return totalRows;
    }
    
    public int getSuccessRows() {
        return successRows;
    }
    
    public int getFailRows() {
        return failRows;
    }
    
    public List<String> getErrorMessages() {
        return errorMessages;
    }
}